package net.pimpas.web.jsf.renderers.html.ajax.wrapper;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.ResponseWriter;

import net.pimpas.web.jsf.components.ajax.context.ResponseWriterAjaxWrapper;
import net.pimpas.xml.serviceprovider.XmlServiceProviderFactoryImpl;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class AjaxHtmlResponseWriterWrapper extends ResponseWriterAjaxWrapper {
	
	private Element root;

	public AjaxHtmlResponseWriterWrapper(ResponseWriter writer) {
		super(writer);
	}
	
	@Override
	protected void initResponse() {
		this.setXmlProvider(XmlServiceProviderFactoryImpl.getXmlServiceProvider());
		// TODO using direct dom4j, no time to implement in pimpas-xml
        this.setDocument(DocumentHelper.createDocument());
	}
	
	@Override
	public void startElement(String name, UIComponent component) throws IOException {
		Element el = null;
		if(this.getRoot() == null) {
			this.setRoot(this.getDocument().addElement(name));
			this.setCurrent(this.getRoot());
			el = this.getCurrent();
		} else
			el = this.getCurrent().addElement(name);
		
		this.setCurrent(el);
	}
	
	@Override
	public void endElement(String name) throws IOException {
		if(this.getCurrent() == null && this.getCurrent() == null) return;
		if(this.getCurrent() == null) this.setCurrent(this.getRoot());
		
		Element parent = this.getCurrent().getParent();
		if(parent == null) parent = this.getRoot();
		this.setCurrent(parent);
	}

	public Element getRoot() {
		return root;
	}

	public void setRoot(Element root) {
		this.root = root;
	}
}